<template>
  <div class="person-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>个人信息</span>
        </div>
      </template>

      <el-form 
        :model="form" 
        label-width="120px"
        ref="formRef"
      >
        <el-form-item label="用户头像">

          <el-upload
            class="avatar-uploader"
            action="http://localhost:9090/api/upload"
            :on-success="handle_success"
          >
            <image 
              v-if="form.avatarUrl" :src="getImageUrl(form.avatarUrl)" >
            </image>


            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>

        <el-form-item label="用户昵称" prop="nickname">
          <el-input v-model="form.nickname" placeholder="请输入昵称" />
        </el-form-item>

        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm">保存修改</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'; // 新增导入
import { ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import { useStore } from 'vuex';
import { updateUserInfo } from '@/api/person'; // 导入封装的API
import { uploadAvatar } from '@/api/upload'; // 新增头像上传API

const store = useStore();
const formRef = ref(null);

// 从 Store 获取当前用户信息
const currentUser = computed(() => store.state.user.userInfo);


// 初始化表单数据
const form = ref({
  id: null,
  avatarUrl: '',
  nickname: '',
  email: ''
});

// 表单验证规则
const rules = {
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 12, message: '长度在2到12个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: ['blur', 'change'] }
  ]
};

// 组件挂载时初始化数据
onMounted(() => {
  if (currentUser.value) {
    form.value = {
      id: currentUser.value.id,
      avatarUrl: currentUser.value.avatar,
      nickname: currentUser.value.nickname,
      email: currentUser.value.email
    };
  }
});

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate();
    
    const response = await updateUserInfo({
      id: form.value.id,
      nickname: form.value.nickname,
      email: form.value.email,
      avatar: form.value.avatarUrl
    });

    if (response.data.code == 200) {
      // 更新 Store 中的用户信息
      store.commit('user/UPDATE_USER_INFO', response.data.data);
      ElMessage.success('信息更新成功');
    }
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '保存失败');
  }
};

// 头像上传处理
const handle_success = (res) => {
  ElMessage.success('图片上传成功');
  form.avatarUrl = res.data; 
   console.log(form.avatarUrl) // 确保接口返回的数据结构匹配
};

const getImageUrl = (fileName) => {
  try {
    // Webpack 需要明确的上下文路径
    console.log(fileName)
    return require(`@/assets/images/${fileName}`);
  } catch (e) {
    return require('@/assets/images/default-avatar.jpg');
  }
};


</script>

<style scoped>
.person-container {
  padding: 20px;
  max-width: 600px;
  margin: 0 auto;
}

.box-card {
  margin-top: 20px;
}

.avatar-uploader {
  :deep(.el-upload) {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
  }

  .avatar {
    width: 120px;
    height: 120px;
    display: block;
  }
}
</style>